package com.qqt.csr.archive.batch.task.etl.reader;

import com.qqt.csr.archive.batch.task.context.MessageArchiveTaskContext;
import com.qqt.csr.archive.batch.task.etl.BaseArchiveReader;
import com.qqt.csr.archive.entity.reader.ArtificialMessage;
import com.qqt.csr.archive.entity.reader.CsrImAccount;
import com.qqt.csr.archive.entity.reader.SmartMessage;
import com.qqt.csr.archive.entity.writer.ArchiveConversation;
import com.qqt.csr.archive.service.ArchiveConversationService;
import com.qqt.csr.archive.service.ArtificialMessageService;
import com.qqt.csr.archive.service.CsrImAccountService;
import com.qqt.csr.archive.service.SmartMessageService;
import com.qqt.csr.common.utils.CacheKeyUtil;
import com.qqt.csr.common.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @Author: yang hao
 * @Date: 2024/11/20 10:17
 * @Description: 消息归档 读取器
 **/
@Slf4j
@Component
@SuppressWarnings("unused")
public class MessageArchiveReader extends BaseArchiveReader<MessageArchiveTaskContext> implements ItemReader<MessageArchiveTaskContext> {

    @Autowired
    private ArchiveConversationService archiveConversationService;
    @Autowired
    private ArtificialMessageService artificialMessageService;
    @Autowired
    private CsrImAccountService csrImAccountService;
    @Autowired
    private SmartMessageService smartMessageService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 读取数据
     * @return {@link MessageArchiveTaskContext} 消息归档任务上下文
     */
    @Override
    public MessageArchiveTaskContext read() {
        MessageArchiveTaskContext context = messageArchiveTaskContexts.poll();
        if (context == null) {
            return null;
        }
        // 根据来源类型处理消息数据读取
        switch (context.getSource()) {
            // 处理人工会话消息数据读取
            case ARTIFICIAL: doArtificialRead(context); break;
            // 处理智能会话消息数据读取
            case SMART: doSmartRead(context); break;
            // 抛出异常
            default: throw new IllegalArgumentException("不支持的来源类型" + context.getSource());
        }
        return context;
    }

    /**
     * 人工会话消息读取
     * @param context {@link MessageArchiveTaskContext} 任务上下文
     */
    private void doArtificialRead(MessageArchiveTaskContext context) {
        // 加载归档会话信息
        // 加载账户消息
        log.debug("开始读取人工会话数据, 上下文:{}", context.toJsonString());
        loadCommonData(context);
        // 根据会话id, 加载会话消息列表
        List<ArtificialMessage> messages = artificialMessageService.getByConversationId(context.getConversation().getConversationId());
        context.setArtificialMessages(messages);
        log.debug("读取人工会话数据完成, 上下文:{}", context.toJsonString());
    }

    /**
     * 智能会话消息读取
     * @param context {@link MessageArchiveTaskContext} 任务上下文
     */
    private void doSmartRead(MessageArchiveTaskContext context) {
        // 读取归档会话消息
        // 加载账户消息
        log.debug("开始读取智能会话数据, 上下文:{}", context.toJsonString());
        loadCommonData(context);
        // 根据会话id, 加载会话消息列表
        List<SmartMessage> messages = smartMessageService.getByConversationId(context.getConversation().getConversationId());
        context.setSmartMessages(messages);
        log.debug("读取智能会话数据完成, 上下文:{}", context.toJsonString());
    }

    /**
     * 加载归档数据
     * @param context {@link MessageArchiveTaskContext} 任务上下文
     */
    private void loadCommonData(MessageArchiveTaskContext context) {
        // 读取归档会话消息
        String conversationKey = String.format(CacheKeyUtil.Archive.CONVERSATION_ARCHIVE, context.getConversationId());
        // 获取会话信息 缓存
        ArchiveConversation conversation = Optional.ofNullable(redissonClient.getBucket(conversationKey).get())
                .map(Object::toString)
                .map(o -> JsonUtil.toObject(o, ArchiveConversation.class))
                .orElse(null);
        // 缓存不存在, 从数据库加载
        if (conversation == null) {
            conversation = archiveConversationService.getByConversationId(context.getConversationId());
            if (conversation == null) {
                throw new IllegalArgumentException("会话不存在" + context.getConversationId());
            }
        }
        context.setConversation(conversation);
        // 加载账户消息
        CsrImAccount csAccount = csrImAccountService.getById(conversation.getCsAccountId());
        context.setCsAccount(csAccount);
        CsrImAccount userAccount = csrImAccountService.getById(conversation.getUserAccountId());
        context.setUserAccount(userAccount);
    }


}
